package cn.hd01.web.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.hd01.repository.entity.Role;
import cn.hd01.service.RoleService;
import cn.hd01.web.auth.Auth;
import cn.hd01.web.util.WebException;

@Controller
@RequestMapping("/role")
@Auth
public class RoleController {

	@Autowired
	private RoleService roleService;

	@RequestMapping(path = "/", method = RequestMethod.GET)
	public String view() {
		return "role";
	}

	@ResponseBody
	@RequestMapping(path = "/list", method = RequestMethod.GET)
	private Page<Role> find(@RequestParam(name = "name", required = false) String name,
			@PageableDefault Pageable pageable) {
		return roleService.find(name, pageable);
	}

	@ResponseBody
	@RequestMapping(path = "/save", method = RequestMethod.POST)
	private void save(Role u) {
		if (u.getId() == null && roleService.exists(u.getName())) {
			throw new WebException(HttpStatus.BAD_REQUEST, "角色名字重复");
		}
		roleService.save(u);
	}

	@ResponseBody
	@RequestMapping(path = "/delete/{id}", method = RequestMethod.GET)
	private void delete(@PathVariable("id") Integer id) {
		roleService.delete(id);
	}

}
